package com.ErpCoreWeb.Common;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Variable
 */
@WebServlet("/Variable")
public class Variable extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Variable() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

        String Action = request.getParameter("Action");
        if (Action == null) Action = "";
        
        if (Action.equalsIgnoreCase("GetData"))
        {
        	GetData();
            return ;
        }
	}

    void GetData()
    {
        String sData = "";
        CVariable Variable = new CVariable(request);
        for(Map.Entry<String, String> entry:CVariable.g_VarName.entrySet()){ 
            sData += String.format("{ \"Name\": \"%s\",\"Desp\":\"%s\"},"
                , entry.getKey(), entry.getValue());
        }

        if(sData.length()>0 && sData.endsWith(","))
        	sData = sData.substring(0, sData.length()-1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, CVariable.g_VarName.size());

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
